﻿using Abp.AutoMapper;
using RMM.Areas.Dtos;
using RMM.Core.Areas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Linq.Extensions;

namespace RMM.Areas
{
    public class AreasAppService: IAreasAppService
    {
        private readonly IAreaService _areaService;

        public AreasAppService(IAreaService areaService)
        {
            _areaService = areaService;
        }


        public async Task<ResultDto> GetList(int b)
        {
            var prov = (await _areaService.GetAll())
                .WhereIf(b == 1, p => p.Status == b && p.LevelType == 1)
                .Where(p => p.ParentID == 0 && !string.IsNullOrWhiteSpace(p.ShortName))
                .ToList()
                .MapTo<List<ProvDto>>();
            var city = (await _areaService.GetAll())
                .WhereIf(b == 1, p => p.Status == b && p.LevelType == 2)
                .Where(p => p.ParentID != 0 && !string.IsNullOrWhiteSpace(p.ShortName))
                .ToList();

            prov.ForEach(p =>
            {
                p.Citys.AddRange(city.Where(x => x.ParentID == p.Id).MapTo<List<CityDto>>());
            });

            //foreach (var item in prov)
            //{
            //    var c = city.Where(p => p.ParentID == item.Id).MapTo<List<CityDto>>();
            //    item.Citys.AddRange(city.Where(p => p.ParentID == item.CodeID).MapTo<List<CityDto>>());
            //}

            return ResultDto.Success(prov);
        }

        public async Task<ResultDto> GetCityList(int b)
        {
            var list = (await _areaService.GetAll())
                .WhereIf(b == 1, p => p.Status == 1)
                .Where(p => p.LevelType == 2 && p.ShortName != "")
                .MapTo<List<CityDto>>();
            var dto = new List<AreaOutPutDto>();

            var pList = new List<char>();
            pList.AddRange(list.Select(p => p.PinYin.First()).OrderBy(p => p).Distinct());
            pList.ForEach(p => 
            {
                var citys = list.Where(x => x.PinYin.StartsWith(p.ToString())).ToList();
                var d = new AreaOutPutDto();
                d.Letter = p.ToString();
                d.Data = citys;
                dto.Add(d);
            });


            return ResultDto.Success(dto);
        }
        
    }
}
